/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.qxp.simplerpc.connect;

import com.qxp.simplerpc.codec.RpcDecoder;
import com.qxp.simplerpc.codec.RpcEncoder;
import com.qxp.simplerpc.entity.InvokerMessage;
import com.qxp.simplerpc.retry.ConnectionListener;
import com.qxp.simplerpc.utils.SimpleRpcProperties;
import io.netty.bootstrap.AbstractBootstrap;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLException;

/**
 * @author qianxiaopeng
 */
@Component
public final class RpcClient extends AbstractConnector implements Runnable {
    private static Logger logger = LoggerFactory.getLogger(RpcClient.class);
    @Autowired
    private SimpleRpcProperties simpleRpcProperties;
    @Autowired
    private RpcClientHandler rpcClientHandler;
    @Autowired
    private ConnectionListener connectionListener;

    private String host;

    private int port;
    @Override
    public void run() {
        // this.init();
        Bootstrap bootstrap = new Bootstrap();
        this.doConnect(bootstrap);
    }

    @Override
    protected void doConnect(AbstractBootstrap abstractBootstrap) {
        SslContext sslCtx = getSsL();
        EventLoopGroup group = new NioEventLoopGroup(simpleRpcProperties.getClientThreadn());
        Bootstrap bootstrap = (Bootstrap) abstractBootstrap;
        try {
            ChannelFuture channelFuture =
                    bootstrap.group(group)
                            .channel(NioSocketChannel.class)
                            .option(ChannelOption.SO_KEEPALIVE, true)
                            .handler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                public void initChannel(SocketChannel ch) throws Exception {
                                    ChannelPipeline p = ch.pipeline();
                                    if (sslCtx != null) {
                                        p.addLast(sslCtx.newHandler(ch.alloc(), simpleRpcProperties.getHost(), simpleRpcProperties.getPort()));
                                    }
                                    p.addLast(
                                            new RpcDecoder(InvokerMessage.class),
                                            new RpcEncoder(InvokerMessage.class),
                                            rpcClientHandler);
                                }
                            })
                           // .connect(simpleRpcProperties.getHost(), simpleRpcProperties.getPort());
                            .connect(host,port);
            channelFuture.addListener(connectionListener);
            channelFuture.sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
           // group.shutdownGracefully();
        }
    }

    @Override
    protected SslContext getSsL() {
        // Configure SSL.
        SslContext sslCtx = null;
        if (simpleRpcProperties.isSsl()) {
            try {
                sslCtx = SslContextBuilder.forClient()
                        .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
            } catch (SSLException e) {
                logger.error("get ssl error,caused by:\n", e);
            }
        }
        return sslCtx;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public RpcClientHandler getRpcClientHandler() {
        return rpcClientHandler;
    }

    public void setRpcClientHandler(RpcClientHandler rpcClientHandler) {
        this.rpcClientHandler = rpcClientHandler;
    }
}
